package com.itheima.web; /**
 * @author Xiao
 * @date 2021/9/3
 */

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        User user = userService.login(username, password);
        if (user != null) {
            //如果勾选复选框，保存用户名密码信息到cookie，7天内有效
            if ("1".equals(remember)) {
                //创建cookie，存储用户名密码
                Cookie c_uname = new Cookie("username",username);
                Cookie c_pwd = new Cookie("password",password);
                //设置存活时间
                c_uname.setMaxAge(60*60*24*7);
                c_pwd.setMaxAge(60*60*24*7);
                //发送cookie到客户端
                response.addCookie(c_uname);
                response.addCookie(c_pwd);
            }
            //如果没有勾选复选框，不保存到客户端，只在当前会话有效，保存到session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/selectAllServlet");
        } else {
            //用户名或密码错误时，转发错误信息提示
            request.setAttribute("login_msg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response); //转发
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
